package cn.melonlib.nars.names.comp.web.ctrl;

import cn.melonlib.cores.commons.exceptions.WorkerServiceException;
import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import cn.melonlib.nars.names.comp.service.FileService;
import cn.melonlib.nars.names.comp.service.NamesService;
import cn.melonlib.nars.names.model.entity.MelonFile;
import cn.melonlib.nars.names.model.entity.MelonNames;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.yaml.snakeyaml.constructor.BaseConstructor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@RestController
@RequestMapping(path = "/nars/file")
public class FileController extends BaseConstructor {

    @Resource
    private NamesService namesService;

    @Resource
    private FileService fileService;

    @GetMapping(path = "download.api")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception{
        MelonNames melonNames=namesService.lookup(request.getParameter("path"));
        if(melonNames instanceof MelonFile) {
            MelonFile melonFile = (MelonFile) melonNames;
            File file = melonFile.file();
            response.setHeader("Location", URLEncoder.encode(file.getName(), StandardCharsets.UTF_8));
            response.setHeader("Content-Disposition", "filename*=UTF-8''" + URLEncoder.encode(melonNames.getName(), StandardCharsets.UTF_8));
            response.setContentLengthLong(file.length());
            response.setContentType(melonFile.getContentType());
            try (InputStream in = new FileInputStream(file);
                 OutputStream out = response.getOutputStream()) {
                StreamUtils.copy(in, out);
            }
        }else{
            throw new WorkerServiceException("没有找到文件");
        }
    }

    @PostMapping(path = {"upload.api"})
    public String upload(MultipartHttpServletRequest request) throws Exception{
        String path=request.getParameter("path");
        MultipartFile file = request.getFile("file");
        try (InputStream in = file.getInputStream()) {
            fileService.storeFile(in, path, file.getOriginalFilename(), file.getSize(), file.getContentType());
        }
        return JsonMap.createMap().append("status",true).append("msg","保存成功").jsonString();
    }
}
